package com.hrpc.compress.impl;

import com.hrpc.compress.Compressor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipCompressorImpl implements Compressor {

    @Override
    public byte[] compress(byte[] bytes) {
        //压缩本质就是将buf作为输入，将结果作为输出，输出到另一个字节数组中
        try( ByteArrayOutputStream baos=new ByteArrayOutputStream();
             GZIPOutputStream gzipOutputStream= new GZIPOutputStream(baos);) {
            gzipOutputStream.write(bytes);
            gzipOutputStream.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("压缩时出现异常！！！");
        }
    }

    @Override
    public byte[] deCompress(byte[] bytes) {
        //压缩本质就是将buf作为输入，将结果作为输出，输出到另一个字节数组中
        try (ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
             GZIPInputStream gzipInputStream=  new GZIPInputStream(bais)){
            byte[] res = gzipInputStream.readAllBytes();
            return res;
        } catch (IOException e) {
            throw new RuntimeException("解压缩时出现异常！！！");
        }
    }
}
